import Vue from 'vue';
import { Watch } from 'vue-property-decorator';

Vue.directive('FormatNumber', {
    bind(el, binding) {
        const validate = {
            init: function(param) {
                switch (param.type) {
                    // case 'integer':
                    //     this.setInteger(param);
                    //     break;
                    case 'gold':
                        this.setGold(param);
                        break;
                    default:
                        console.log('暂不支持此格式化方式');
                        break;
                }
            },

            setGold: function(param) {
                const input$ = el.getElementsByTagName('input')[0];
                // const funChange = () => {
                //     input$.value = this.goldChange(input$.value);
                //     param.obj[param.key] = input$.value;
                // };
                const funFocus = () => {
                    input$.value = this.goldFocus(input$.value, param.includeZero);
                    param.obj[param.key] = input$.value;
                };
                const funBlur = () => {
                    input$.value = this.goldBlur(input$.value, param.includeZero);
                    param.obj[param.key] = input$.value;
                };

                // validate.addEvent(input$, ['input'], funChange);
                validate.addEvent(input$, ['blur'], funBlur);
                validate.addEvent(input$, ['focus'], funFocus);
            },

            addEvent(el, eventName, eventFn) {
                eventName.forEach(name => {
                    el.addEventListener(eventName, eventFn);
                });
            },

            goldChange(value) {
                // let newValue = v.toString();
                // newValue = v
                //     .replace(/[^\d.]/g, '')
                //     .replace(/\.{2,}/g, '.')
                //     .replace('.', '$#$')
                //     .replace(/\./g, '')
                //     .replace('$#$', '.')
                //     .replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
                // if (newValue.length > 1 && newValue.indexOf('.') !== 1 && newValue.indexOf('0') === 0) {
                //     newValue = newValue.toString().substring(1);
                // }
                // return newValue;
            },

            goldFocus(num) {
                if (num && num != undefined && num != null) {
                    let _num = num;
                    _num = _num.replace(/,/gi, '');
                    return _num;
                } else {
                    return num;
                }
            },
            goldBlur(value) {
                let newValue = value;
                if (value) {
                    newValue = Number(value).toLocaleString();
                }
                return newValue;
            },
        };
        validate.init(binding.value);
    },
});
